<template>
  <div class="cangwei-container">
    <!-- 顶部操作栏 -->
    <div class="header-section">
      <div class="toolbar-right">
        <el-button type="primary" @click="handleAdd" style="background-color: #ff4d4f; border-color: #ff4d4f;">
          <el-icon><Plus /></el-icon>
          新建
        </el-button>
        <!-- 添加导出按钮 -->
        <el-button type="primary" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
        <!-- 添加批量删除按钮 -->
        <el-button type="danger" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </div>
    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        :data="cangweiList"
        style="width: 100%"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
          <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="chuNo" label="编码" min-width="120" />
      <el-table-column prop="chuName" label="名称" min-width="150" />
      <el-table-column prop="cangKuName" label="所属库位" min-width="120" />
      <el-table-column prop="mShu" label="描述" min-width="150" />
      <el-table-column prop="createName" label="创建人" min-width="120" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ scope.row.createTime ? moment(scope.row.createTime).format('YYYY-MM-DD') : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #default="scope">
          {{ scope.row.updateTime ? moment(scope.row.updateTime).format('YYYY-MM-DD') : '' }}
        </template>
      </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="text" class="action-btn" @click="handleEdit(row)" title="编辑">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="text" class="action-btn delete-btn" @click="handleDelete(row)" title="删除">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <div class="pagination-info">共 {{pagination.totalCount}} 条数据</div>
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="prev, pager, next, sizes, jumper"
          :total="pagination.totalCount"
        />
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="cangweiFormRef"
        :model="formData"
        label-width="120px"
      >
        <el-form-item label="储位编码" prop="chweiNo">
          <el-input v-model="formData.chuNo" placeholder="请输入储位编码" />
        </el-form-item>
        <el-form-item label="储位名称" prop="chweiName">
          <el-input v-model="formData.chuName" placeholder="请输入储位名称" />
        </el-form-item>
        <el-form-item label="所属库位" >
          <el-select v-model="formData.kuWeiId" placeholder="请选择对应的库位">
            <el-option
              v-for="item in cangkuList"
              :label="`${item.cangNo}|${item.cangKuName}`"
              :value="item.cangKuId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="mShu">
          <el-input v-model="formData.mShu" placeholder="请输入描述" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { APIs } from '../../Http/http'
import { Edit, Delete, Plus, Download } from '@element-plus/icons-vue'
import moment from 'moment'
import { saveAs } from 'file-saver'

// 表格数据
const cangweiList = ref<any[]>([])
// 仓库/库区列表
const cangkuList = ref<any[]>([])
// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('新建仓位')
const cangweiFormRef = ref()

// 表单数据
const formData = reactive({
  "chuNo": "",
  "chuName": "",
  "kuWeiId": null,
  "mShu": "",
  "createName": ""
})

onMounted(() => {
  getCangWeiList()
  getCangKuList()
})

// 获取仓位列表
const getCangWeiList = async () => {
  const response = await APIs.get('/api/Read/GetChuWeiWithCangKuQU', {
    params: {
      pageindex: pagination.pageIndex,
      pageSize: pagination.pageSize,
    }
  })
  
  if (response.data.code === 100) {
    cangweiList.value = response.data.data.data
    pagination.totalCount = response.data.data.totalCount
    console.log(response.data.data.totalCount)
  }
}

// 获取仓库/库区列表
const getCangKuList = async () => {
  const response = await APIs.get('/api/Read/GetCangKuquList')
  if (response.data.code === 100) {
    cangkuList.value = response.data.data
  }
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新建仓位'
  Object.assign(formData, {
    "chuNo": "",
    "chuName": "",
    "cangName": null,
    "mShu": "",
    "createName": ""
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑仓位'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除仓位 "${row.cangKuName}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    APIs.post('/api/Write/DeleChuwei',row).then(() => {
      ElMessage.success('删除成功')
      getCangWeiList()
    })
  })
}

// 保存表单
const handleSave = () => {
  if (!cangweiFormRef.value) return
  
  cangweiFormRef.value.validate().then(() => {
    const submitData = {
      ...formData
    }
    
    if (dialogTitle.value === '编辑仓位') {
      APIs.post('/api/Write/UpdateChuwei', submitData).then(response => {
        if (response.data.code === 100) {
          ElMessage.success('更新成功')
          dialogVisible.value = false
          getCangWeiList()
        } else {
          ElMessage.error('更新失败')
        }
      })
    } else {
      APIs.post('/api/Write/AddChuwei', submitData).then(response => {
        if (response.data.code === 100) {
          ElMessage.success('新增成功')
          dialogVisible.value = false
          getCangWeiList()
        } else {
          ElMessage.error('新增失败')
        }
      })
    }
  })
}

// 导出Excel功能
const handleExport = async () => {
  
  try {
    // 使用您提供的导出接口
    const response = await APIs.get('/api/Read/ChuExcel', {
      responseType: 'blob', // 重要：设置响应类型为blob
      timeout: 30000 // 设置超时时间
    })
    
    // 创建Blob对象
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    
    // 生成带时间戳的文件名
    const timestamp = moment().format('YYYYMMDD_HHmmss')
    const fileName = `仓位数据_${timestamp}.xlsx`
    
    // 保存文件
    saveAs(blob, fileName)
    
    // 显示成功提示
    ElMessage.success('数据导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}
const selectedRows = ref<any[]>([])
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
  console.log(selectedRows.value);
};
const getSelectedRowsArray = () => {
  return selectedRows.value.map(row => ({
    id: row.chuId,
  }));
};

// 实现批量删除功能
const handleBatchDelete = () => {
  const selectedIds = getSelectedRowsArray();
  const requestData = {
    ids: selectedIds.map(item => item.id)
  };
  
  ElMessageBox.confirm(
    `确定要删除选中的${selectedRows.value.length}个车间吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    APIs.post("/api/Write/plDeleChuwei", requestData).then(res=>{
      if(res.data.code==100) {
        ElMessage.success("批量删除成功");
       getCangWeiList();    
      }
    })
  });
};
const handleDialogClose = () => {
  if (cangweiFormRef.value) {
    cangweiFormRef.value.resetFields()
  }
  dialogVisible.value = false
}

watch(pagination,()=>{
  getCangWeiList()
})
</script>

<style scoped>
.cangwei-container {
  background: white;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header-section {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 15px 20px;
  background-color: #fafafa;
  border-bottom: 1px solid #e4e7ed;
}

.toolbar-right {
  display: flex;
  gap: 10px;
}

.search-section {
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-section {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

.action-btn {
  color: #409eff;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #ff8585;
}

/* 自定义下拉框样式 */
.el-select-dropdown__item {
  display: flex;
  justify-content: space-between !important;
}
</style>